package com.acce.core.utils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class Utils {
	
	private static Logger logger = Logger.getLogger(Utils.class);
	
	public static String sendhttp(String serviceAddr, Map<String, String> params){
		String returnString = "";
		logger.info("sendhttp::serviceAddr::" + serviceAddr);
		// 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try{
        	// 创建httppost  
	        HttpPost httppost = new HttpPost(serviceAddr);
	        List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
	        Iterator<String> it = params.keySet().iterator();
	        while(it.hasNext()){
	        	String key = it.next();
	        	String value = params.get(key);
	        	formparams.add(new BasicNameValuePair(key,value));
	        }
	        logger.info("sendhttp::params::" + formparams.toString());
	        UrlEncodedFormEntity uefEntitygs = new UrlEncodedFormEntity(formparams,"UTF-8");
	        httppost.setEntity(uefEntitygs); 
	        CloseableHttpResponse response = httpclient.execute(httppost);  //发送post请求并响应的内容
			try {
				HttpEntity entity = response.getEntity(); 
	            returnString=EntityUtils.toString(entity, "UTF-8");
	            logger.info("sendhttp::return content::" + returnString);
			} catch (Exception e) {
				logger.info("sendhttp erroe::" + e.getMessage());
			}finally{
				response.close();
			}
        }catch(Exception e){
        	logger.info("sendhttp erroe::" + e.getMessage());
        }finally{
        	 // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {
            	logger.info("sendhttp not close::" + e.getMessage());
            }  
        }
        return returnString;
	}
	
	public static String getSMSCode(){
		StringBuffer fm = new StringBuffer(); 
		Random r = new Random();
		for(int i = 0; i < 4; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}

	/**
	 * ��ȡ��ǰʱ��
	 * @return  yyyy-MM-dd HH:mm:ss
	 */
	public static String getCurrTime() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(new Date());
	}
	
	/**
	 * ��ȡ��ǰʱ��
	 * @return  yyyy-MM-dd HH:mm:ss
	 */
	public static String getCurrTimeMillions() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		return df.format(new Date());
	}
	
	/**
	 * ��ȡʱ�����λΪ��
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static String timeDifs(long d1, long d2){
		long mss = d2 - d1;
		long days = mss / (1000 * 60 * 60 * 24);  
	    long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);  
	    long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);  
	    long seconds = (mss % (1000 * 60)) / 1000;  
	    return days + "-" + hours + "-" + minutes + "-"  
		            + seconds;
	}
	
	/**
	 * �ı�ʱ��
	 * @param time ʱ��
	 * @param oper ���������ӻ����j/s
	 * @param timeType ʱ�����ͣ�������ʱ���� Y/M/D/h/m/s
	 * @param num �ı�ʱ����
	 * @return
	 * @throws ParseException 
	 */
	public static String timeChange(String time, String oper, String timeType, int num) throws ParseException{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = df.parse(time);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		if("j".equals(oper)){
			if("Y".equals(timeType)){
				c.add(Calendar.YEAR, num);
			}
			if("M".equals(timeType)){
				c.add(Calendar.MONTH, num);
			}
			if("D".equals(timeType)){
				c.add(Calendar.DAY_OF_MONTH, num);
			}
			if("h".equals(timeType)){
				c.add(Calendar.HOUR_OF_DAY, num);
			}
			if("m".equals(timeType)){
				c.add(Calendar.MINUTE, num);
			}
			if("s".equals(timeType)){
				c.add(Calendar.SECOND, num);
			}
		}else if("s".equals(oper)){
			if("Y".equals(timeType)){
				c.add(Calendar.YEAR, -num);
			}
			if("M".equals(timeType)){
				c.add(Calendar.MONTH, -num);
			}
			if("D".equals(timeType)){
				c.add(Calendar.DAY_OF_MONTH, -num);
			}
			if("h".equals(timeType)){
				c.add(Calendar.HOUR_OF_DAY,-num);
			}
			if("m".equals(timeType)){
				c.add(Calendar.MINUTE, -num);
			}
			if("s".equals(timeType)){
				c.add(Calendar.SECOND, -num);
			}
		}
		return df.format(c.getTime());
	}
	
	/**
	 * ����ũ�̺�,����Ϊ:KL+��ݺ���λ+��+����+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeAtUserId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("KL");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * ������˾��,����Ϊ:CP+��ݺ���λ+��+����+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeCompanyId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("CP");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * ������˾��,����ΪDP+���+��+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeDepartmentId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("DP");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * ����������,����ΪPW+���+��+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makePasswordId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("PW");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String getUUID(){
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replaceAll("-", "");
	}
	
	public static String makeNotifyId(){
		return getUUID();
	}
	
	/**
	 * ��ȡ��������IP��ַ,���ͨ�������������͸������ǽ��ȡ��ʵIP��ַ;
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public final static String getIpAddress(HttpServletRequest request) throws IOException {
		// ��ȡ��������IP��ַ,���ͨ�������������͸������ǽ��ȡ��ʵIP��ַ

		String ip = request.getHeader("X-Forwarded-For");
		if (logger.isInfoEnabled()) {
			logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
				}
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
				if (logger.isInfoEnabled()) {
					logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
				}
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}
	
	public static String serviceMapping(String type, String source){
		String target = null;
		if("u".equals(type.toLowerCase())){
			target = source.replace("A", "U");
		}
		return target;
	}
	
	/**
	 * ����������־Id,����ΪOP+���+��+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeOperId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("OP");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	/**
	 * ������¼��־Id,����ΪLG+���+��+��λ�����,��ʮ��λ��
	 * @return
	 */
	public static String makeLoginId(){
		SimpleDateFormat df = new SimpleDateFormat("yyssSSS");
		StringBuffer fm = new StringBuffer(); 
		fm.append("LG");
		fm.append(df.format(new Date()));
		Random r = new Random();
		for(int i = 0; i < 6; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static String getNonce(){
		StringBuffer fm = new StringBuffer(); 
		Random r = new Random();
		for(int i = 0; i < 9; i++){
			fm.append(r.nextInt(9));
		}
		return fm.toString();
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(makeAtUserId());
//		SimpleDateFormat myFormatter = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss");
//		Date d1 = myFormatter.parse("2016-05-26 10:01:30");
//		Date d2 = myFormatter.parse("2016-05-27 11:05:50");
//		System.out.println(timeDifs(d1, d2));
		
//		JSONObject j = new JSONObject();
//		
//		List<String> list = new ArrayList<String>();
//		list.add("1");
//		list.add("2");
//		list.add("3");
//		System.out.println(j.toJSONString(list));
//		
//		List<Prop> list2 = new ArrayList<Prop>();
//		Prop p = new Prop();
//		p.setId("1");
//		p.setKey("k");
//		p.setValue("v");
//		list2.add(p);
//		System.out.println(j.toJSONString(list2));
//		
//		Map<String, String> m = new HashMap<String, String>();
//		m.put("1", "v");
//		m.put("2", "n");
//		System.out.println(j.toJSONString(m));
//		
//		JSONObject j2 = new JSONObject();
//		
//		DepartTree dt = new DepartTree();
//		dt.setCorpCode("1");
//		dt.setSon("b1");
//		
//		List<DepartTree> c1 = new ArrayList<DepartTree>();
//		
//		DepartTree dt2 = new DepartTree();
//		dt2.setCorpCode("2");
//		dt2.setSon("b2");
//		dt2.setChildren(null);
//		
//		DepartTree dt3 = new DepartTree();
//		dt3.setCorpCode("3");
//		dt3.setSon("b3");
//		dt3.setChildren(null);
//		
//		c1.add(dt2);
//		c1.add(dt3);
//		dt.setChildren(c1);
//		System.out.println(j2.toJSONString(dt));
//		
//		System.out.println(Utils.makeFarmerMerchants());
	}
}
